import axios from 'axios';

import { Message } from 'element-ui';

axios.defaults.withCredentials = true
import { Loading } from 'element-ui';


// const downloadFile = (method = 'get', url, params = {}) => {
//   return axios({
//     method: method,
//     url: calc(url),
//     responseType: 'blob',
//     headers: {
//       token: localStorage.getItem('logintoken'),
//     },
//     data: method.toLowerCase() === 'post' ? params : undefined,
//     params: method.toLowerCase() === 'get' ? params : undefined,
//   }).then(response => {
//     const disposition = response.headers['content-disposition'];
//     let filename = '下载文件.xlsx';
//     if (disposition) {
//       const match = disposition.match(/filename\*?=([^;]+)/);
//       if (match && match[1]) {
//         filename = decodeURIComponent(match[1].replace(/UTF-8''/, '').trim());
//       }
//     }

//     const blob = new Blob([response.data], {
//       type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
//     });

//     const link = document.createElement('a');
//     link.href = window.URL.createObjectURL(blob);
//     link.download = filename; // ✅ 使用后端指定的文件名
//     document.body.appendChild(link);
//     link.click();
//     link.remove();
//   }).catch(error => {
//     console.error('下载失败', error);
//   });
// };


const downloadFile = (method = 'get', url, params = {}) => {
  let loadingInstance = Loading.service({
    fullscreen:true,
    text:'数据导出中请稍等',
    background:'rgba(0,0,0,0.6)'
  });
  return axios({
    method: method,
    url: calc(url),
    responseType: 'blob', // 保持 blob 以兼容流式
    headers: {
      token: localStorage.getItem('logintoken'),
    },
    data: method.toLowerCase() === 'post' ? params : undefined,
    params: method.toLowerCase() === 'get' ? params : undefined,
  }).then(response => {
    const disposition = response.headers['content-disposition'];
    let filename = '数据导出.csv';

    if (disposition) {
      const match = disposition.match(/filename\*?=([^;]+)/);
      if (match && match[1]) {
        filename = decodeURIComponent(match[1].replace(/UTF-8''/, '').trim());
      }
    }

    const blob = new Blob([response.data], { type: 'text/csv;charset=utf-8;' });

    const link = document.createElement('a');
    const url = window.URL.createObjectURL(blob);
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    loadingInstance.close();
  }).catch(error => {
    console.error('CSV 下载失败:', error);
  });
};


// 前端不做api处理, 所有接口(除了login)数据及参数全部由后端提供,前端仅解析数据

// 登录请求方法
const loginreq = (method, url, params) => {
  return axios({
    method: method,
    url: url,
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    data: params,
    traditional: true,
    transformRequest: [
      function (data) {
        if (this.headers['Content-Type'] == 'application/json') {
          return JSON.stringify(data)
        }
        else if (this.headers['Content-Type'] == 'application/x-www-form-urlencoded') {
          let ret = ''
          for (let it in data) {
            ret +=
              encodeURIComponent(it) +
              '=' +
              encodeURIComponent(data[it]) +
              '&'
          }
          return ret
        }
      }
    ]
  }).then(res => res.data);
};

function calc(url) {
  // if (url.includes("?")) {
  //   url += "userloginId=" + localStorage.getItem("id")
  // }
  // else {
  //   url += "?userloginId=" + localStorage.getItem("id")
  // }
  url = processUrlParams(url)
  if(url.startsWith("/bpi")){

    return     url; // lp环境
  }
  if (process.env.NODE_ENV === 'development') {
    return '/api' + url; // 开发环境
  } else {
    return url; // 生产环境
  }
};


// 转换查询是前端的时间字符串
function processUrlParams(url) {
  const formatDate = (date) => {
  date = new Date(date);

  // 使用 Intl.DateTimeFormat 格式化日期，确保按指定格式输出
  const options = {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false, // 24小时制
    timeZone: 'UTC' // 强制转换为 UTC 时区，避免时区转换问题
  };

    // 使用 UTC 时区来避免时区影响
    const formatter = new Intl.DateTimeFormat("zh-CN", options);  // 使用 en-GB 可以避免月和日的位置翻转
    const formattedDate = formatter.format(date);
    console.log(`formattedDate==>${formattedDate}`)
    return formattedDate; // 返回格式化后的日期
  };

  // 注意所有的时间查询均以_end, _start 结尾
  const isTimeField = (key) => {
    return key.endsWith('_start') || key.endsWith('_end');
  };

  const [baseUrl, queryString] = url.split('?');
  if (!queryString) return url;

  const rawParams = new URLSearchParams(queryString);
  const newParams = new URLSearchParams();

  for (let [key, value] of rawParams.entries()) {

    if (isTimeField(key) && value && value != 'null') {
      const formatted = formatDate(value);
      newParams.set(key, formatted); // 保留原始格式，避免自动转义 %20、%3A
    } else {

      if(isTimeField(key)){
        continue
      }
      else if(value != 'null') {
        newParams.set(key, value); // 保留其他参数
      }
    }
  }

  return `${baseUrl}?${newParams.toString()}`;
}

// 通用公用方法
const req = (method, url, params) => {
  return axios({
    method: method,
    url: calc(url),
    headers: {
      'Content-Type': 'application/json', // 设置传输格式为json
      token: localStorage.getItem('logintoken'),
      dataType: 'json',
      withCredentials: true,
    },
    data: params,
    traditional: true,
    transformRequest: [
      function (data) {
        if (this.headers['Content-Type'] == 'application/json') {
          return JSON.stringify(data)
        }
        else if (this.headers['Content-Type'] == 'application/x-www-form-urlencoded') {
          let ret = ''
          for (let it in data) {
            ret +=
              encodeURIComponent(it) +
              '=' +
              encodeURIComponent(data[it]) +
              '&'
          }
          return ret
        }
      }
    ]
  }).then(res => res.data);
};

axios.interceptors.response.use(res => {

  // 请求成功对响应数据做处理
  // 该返回的数据则是axios.then(res)中接收的数据

  if (res.data instanceof Blob){

  }
  else {
    if (res.data.code != 200) {
      Message.error(res.data.msg)
    }
  }
  return res
}, err => {
  // 在请求错误时要做的事儿
  // 该返回的数据则是axios.catch(err)中接收的数据
  return Promise.reject(err)
})


export {
  loginreq,
  req,
  downloadFile
}

//  req("post", "/Goods/list", params)
//  req("post", "/Goods/list", params) };
//  req("post", "/Goods/save", params) };
//  return axios.delete("/api/Goods/delete?ids=" + params + "&token=" + localStorage.getItem('logintoken')).then(res => res.data) };
